﻿package {
	import flash.display.*;
	import flash.net.*;
	import flash.system.*;
	import flash.external.*;
	import flash.utils.*;
	
	public class Pixel extends Sprite {
		private var cookie:SharedObject;
		private var clientid:String;
		private var tag:XML = <tag><![CDATA[
			var str = "clientid={id}";
			var date = new Date();
			date.setTime(date.getTime() + 1000 * 3600 * 24 * 365);
			str += "; expires=" + date.toGMTString();
			document.cookie = str;
		]]></tag>;

		public function Pixel():void {
			Security.allowDomain("*");
			try {
				cookie = SharedObject.getLocal("pixel_local_data");
			} catch(e:Error) {
			}
			//
			clientid = getClientId();
			//trace(clientid);
			var str:String = tag.text();
			str = str.replace(/\/\/.*\s/ig, "");
			str = str.replace(/\r|\n/ig, "");
			str = str.replace("{id}", clientid);
			//trace(str);
			
			//ready
			//fixed wmode transparent
			setTimeout(function(){
				eic("eval", str);
				eic("pixel_ready", clientid);      
			}, 10);
			
			//add callback
			if (ExternalInterface.available) {
				ExternalInterface.addCallback("execute", execute);
			}
		}
		
		public function execute(... rest):Object {
			if (rest[0]) {
				if (rest.length > 1) {
					setCookie(rest[0], rest[1]);
				} else {
					return getCookie(rest[0]);
				}
			}
			return clientid;
		}
		
		private function eic(fn:String, v:String):void {
			if (!ExternalInterface.available) {
				return;
			}
			try {
				ExternalInterface.call(fn, v);
			} catch (e:Error) {
			}
		}
		
		private function setCookie(n:String, v:Object):void {
			if (cookie) {
				cookie.data[n] = v.toString();
			}
		}
		private function getCookie(n:String):Object {
			if (cookie) {
				return cookie.data[n];
			}
			return "";
		}
		
		private function getClientId():String {
			var cid:String = String(getCookie("clientid"));
			if (cid.length == 32) {
				return cid;
			}
			var nid:String = MD5.hash(Math.random().toString().substr(2)).toUpperCase();
			setCookie("clientid", nid);
			return nid;
		}

	}
}